package com.power.ding.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.utils.StringUtil;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.ding.dao.Di_rel_dept_correctDao;
import com.power.ding.model.Di_rel_dept_correct;
import com.power.ding.model.Di_user;
import com.power.ding.model.pageInfo.Di_rel_dept_correctPageInfo;
import com.power.ding.model.pojo.bo.Di_rel_dept_BaseUser;
import com.power.ding.service.Di_rel_dept_correctService;
import com.power.ding.service.Di_userService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 司法社矫组织机构表业务层实现
 */
@Service
public class Di_rel_dept_correctServiceImpl extends BaseServiceImpl implements Di_rel_dept_correctService {

    @Autowired
    private Di_rel_dept_correctDao dao;

    @Autowired
    private Di_userService diUserService;

    @Override
    public Di_rel_dept_correct getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Di_rel_dept_correct di_rel_dept_correct) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (di_rel_dept_correct.getPrimaryKey() != null) {
            Di_rel_dept_correct di_rel_dept_correctfDb = dao.findById(di_rel_dept_correct.getPrimaryKey()).orElse(null);
            if (di_rel_dept_correctfDb != null) {
                BeanUtils.copyProperties(di_rel_dept_correct, di_rel_dept_correctfDb);
                dao.save(di_rel_dept_correctfDb);
                return;
            }
        }
        dao.save(di_rel_dept_correct);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Di_rel_dept_correct> findAll(Di_rel_dept_correctPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Di_rel_dept_correct> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Di_rel_dept_correct> list) {
        dao.saveAll(list);
    }

    @Override
    public List<Map<String, Object>> getQueryTree() {
        // 查出所有数据
        List<Di_rel_dept_correct> diRelDeptSfList = this.dao.findAll();

        //找到一级菜单
        List<Map<String, Object>> level1 = diRelDeptSfList.stream().filter(item -> StringUtil.isEmpty(item.getFid())).map(
                (menu) -> {
                    Map<String, Object> menuMap = BeanUtil.beanToMap(menu);
                    menuMap.put("children", getChildrens(menuMap, diRelDeptSfList));
                    return menuMap;
                }
        ).sorted((menu1, menu2) -> {
            //排序
            return ((String) menu1.get("orgname")).compareTo(((String) menu2.get("orgname")));
        }).collect(Collectors.toList());
        return level1;
    }
    //递归查找所有菜单的子菜单
    public List<Map<String, Object>> getChildrens(Map<String, Object> root, List<Di_rel_dept_correct> all) {
        List<Map<String, Object>> children = all.stream().filter(item -> {
            return ((String) root.get("id")).equals(item.getFid());
        }).map(item -> {
            //找到子菜单
            Map<String, Object> itemMap = BeanUtil.beanToMap(item);
            itemMap.put("children", getChildrens(itemMap, all));
            return itemMap;
        }).sorted((menu1, menu2) -> {
            //排序
            return ((String) menu1.get("orgname")).compareTo(((String) menu2.get("orgname")));
        }).collect(Collectors.toList());
        return children;
    }


    @Override
    public PageDataResponse queryPageDeptAndUser(Di_rel_dept_correctPageInfo pageInfo) {
        List<Map<String, Object>> list = this.dao.queryPageDeptAndUser(pageInfo);

        // 2.分页
        PageDataResponse page = new PageDataResponse();
        if (!CollectionUtils.isEmpty(list)) {

            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                Integer num = pageInfo.getPageNumber() + 1;
                page.setNextPage(num);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
            page.setRecords(list);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
            page.setRecords(list);
        }
        return page;
    }

    @Override
    public List<Di_rel_dept_BaseUser> queryBaseOrgUser() {
        List<Map<String,Object>> baseOrgUsers = dao.queryBaseOrgUser();
        if (CollectionUtil.isNotEmpty(baseOrgUsers)) {
            return JSON.parseArray(JSON.toJSONString(baseOrgUsers), Di_rel_dept_BaseUser.class);
        }
        return Collections.emptyList();
    }

    @Override
    public List<Map<String, Object>> queryBaseOrgTree() {
        List<Map<String,Object>> baseOrgMapList = this.dao.queryBaseOrg();
        List<Di_rel_dept_BaseUser> baseOrgUser = this.queryBaseOrgUser();
        if (CollectionUtil.isNotEmpty(baseOrgMapList) && CollectionUtil.isNotEmpty(baseOrgUser)) {
            List<Map<String, Object>> treeDataList = new ArrayList<>();
            for (Map<String,Object> diDept : baseOrgMapList) {
                Map<String, Object> treeData = new HashMap<>();
                treeData.put("id", diDept.get("id"));
                treeData.put("name", diDept.get("orgname"));

                List<Di_rel_dept_BaseUser> filterUser = baseOrgUser.stream().filter(el -> el.getOrgid().equals(diDept.get("id"))).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(filterUser)) {
                    List<Map<String, Object>> childTreeDataList = new ArrayList<>();
                    filterUser.stream().forEach(el -> {
                        Map<String, Object> childTreeData = new HashMap<>();
                        childTreeData.put("id", el.getUserid());
                        childTreeData.put("name", el.getUsername());
                        childTreeData.put("pid", diDept.get("id"));
                        childTreeDataList.add(childTreeData);
                    });
                    treeData.put("children",childTreeDataList);
                }
                treeDataList.add(treeData);

            }
            return treeDataList;
        }
        return Collections.emptyList();
    }

    @Override
    public void updataContactuser(Di_rel_dept_correct diRelDeptCorrect) {
        Di_rel_dept_correct dept_correct = dao.getById(diRelDeptCorrect.getId());
        Di_user diUser = diUserService.getById(dept_correct.getContactuser());
        Assert.notNull(diUser,"不存在用户");
        dept_correct.setContactuser(diRelDeptCorrect.getContactuser());
        dao.save(dept_correct);
    }

    @Override
    public Di_user queryDeptAndUserById(String id) {
        Di_rel_dept_correct daoById = dao.getById(id);
        Di_user diUser = diUserService.getById(daoById.getContactuser());
        return diUser;
    }

    @Override
    public List<Di_rel_dept_BaseUser> queryBaseOrgUserByUser(Di_rel_dept_BaseUser baseUser) {
        List<Map<String,Object>> baseOrgUsers = dao.queryBaseOrgUserByUser(baseUser);
        if (CollectionUtil.isNotEmpty(baseOrgUsers)) {
            return JSON.parseArray(JSON.toJSONString(baseOrgUsers), Di_rel_dept_BaseUser.class);
        }
        return Collections.emptyList();
    }
}
